// pages/home/home.js
var QQMapWX = require('../../third/qqmap/qqmap-wx-jssdk.js');
var qqmapsdk;
var appkey = "6ad1374482bf670c55b6e39ec960fea4";
var util = require("../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    weather: {
      hourly_forecast: [],
      daily_forecast: [],
      now: {
        tmp: "0",
        hum: "0",
        vis: "0",
        pres: "0",
        wind: {
          dir: "无风",
          sc: "0",
          spd: "0"
        },
        cond: {
          txt: "晴"
        }
      },
      astro: {
        sr: "06:36", // 日出时间
        ss: "17:24" // 日落时间
      },
      aqi: {
        aqi: "0",
        qlty: "优"
      },
      suggestion: [],
      updateTime: util.formatTime(new Date()),
    },
    location: "",
    updateTimeHidden: true,
    isNight: false, 
    isChoose: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    qqmapsdk = new QQMapWX({
      key: "FHMBZ-7IGRF-3XPJT-JS4Q6-YPFQQ-Q3FZJ"
    });

    var nowDay = new Date();
    var hours = nowDay.getHours();
    if (hours < 19) {
      this.setData({
        isNight: false
      });
    } else {
      this.setData({
        isNight: true
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this
    var weather = wx.getStorageSync("weather") || this.data.weather
    var location = wx.getStorageSync("location") || "商丘"
    this.setData({
      weather: {
        hourly_forecast: weather.hourly_forecast,
        daily_forecast: weather.daily_forecast,
        aqi: weather.aqi,
        now: weather.now,
        astro: weather.astro,
        suggestion: weather.suggestion,
        updateTime: weather.updateTime
      },
      location: location,
      updateTimeHidden: true,
      isNight: false
    })  

    this.getLocation();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  bindload: function (event) {
    console.log(event)
  },

  binderror: function (event) {
    console.log(event)
  },

  // 定位函数
  getLocation: function() {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });

        that.getAddress(res.latitude, res.longitude, function(address, city) {
          that.getWeather(city);
          // 用于显示
          that.setData({
            location: address,
          });
        });
      },
      fail: function(res) {
        wx.hideNavigationBarLoading();
        wx.showToast({
          title: '定位失败，请重新启动',
          icon: 'none'
        });
      }
    });
  },

  // 逆地理编码函数 通过经纬度获取地理位置
  getAddress: function (latitude, longitude, callback) {
    var that = this
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        // 解析成功返回地址 
        // 存储地理位置
        var location = res.result.formatted_addresses.recommend
        var city = res.result.address_component.district
        if (that.data.isChoose == false) {
          wx.setStorageSync("location", location)
          wx.setStorageSync("city", city)
        }
        callback(location, city)
      },
      fail: function (res) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        wx.showToast({
          title: '定位失败，请重新启动',
          icon: 'none'
        });
      },
      complete: function (res) {

      }
    });
  },

  // 获取天气信息 全国天气接口
  getCountryWeather: function(city) {
    var that = this;
    var url = 'https://way.jd.com/jisuapi/weather?city=' + city + '&appkey=' + appkey;
    wx.request({
      url: url,
      success(res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (res.data.code == "10000") {
          console.log(res.data.result);

          var weatherData = res.data.result;
          if (weatherData.status == "ok") {
            that.analysisCountryData(weatherData);
          } else {
            wx.showToast({
              title: '暂无此地区天气信息',
              icon: 'none'
            })
          }
        }
      },
      fail(res) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        wx.showToast({
          title: '天气加载失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取天气信息 世界天气接口
  getWeather: function(city) {
    var that = this;
    var url = 'https://way.jd.com/he/freeweather?city=' + city + '&appkey=' + appkey;
    wx.request({
      url: url,
      success(res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (res.data.code == "10000") {
          var weatherData = res.data.result.HeWeather5[0];
          if (weatherData.status == "ok") {
            that.analysisData(weatherData);
          } else {
            wx.showToast({
              title: '暂无此地区天气信息',
              icon: 'none'
            })
          }
        }
      },
      fail(res) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        wx.showToast({
          title: '天气加载失败',
          icon: 'none'
        });
      }
    });
  },

  analysisCountryData: function(weather) {
    var that = this;
    var str = JSON.stringify(weather);
    var hourly_forecast = [];
    hourly_forecast.push({
      date: "现在",
      cond: weather.now.cond,
      tmp: weather.now.tmp
    });
    // 24小时 数组
    for (var i = 0; i < weather.hourly.length; i++) {
      var hourDic = weather.hourly_forecast[i];
      hourDic.date = hourDic.date.substr(11, 5);
      hourly_forecast.push(hourDic);
    }

    // 7天天气 数组
    var daily_forecast = [];
    // 使用forEach遍历
    weather.daily.forEach(function (dailyDic) {
      dailyDic.week = util.dateLater(dailyDic.date, 0);
      daily_forecast.push(dailyDic);
    });

        // 生活指数数组 按照指定顺序排列
        var suggestion = [];
      suggestion.push(weather.index);

  },

  // 解析天气信息函数 构建数据赋值
  analysisData: function(weather) {
    var that = this;
    var str = JSON.stringify(weather);
    var hourly_forecast = [];
    hourly_forecast.push({
      date: "现在",
      cond: weather.now.cond,
      tmp: weather.now.tmp
    });
    // 24小时 数组
    for (var i = 0; i < weather.hourly_forecast.length; i++) {
      var hourDic = weather.hourly_forecast[i];
      hourDic.date = hourDic.date.substr(11, 5);
      hourly_forecast.push(hourDic);
    }

    // 7天天气 数组
    var daily_forecast = [];
    // 使用forEach遍历
    weather.daily_forecast.forEach(function (dailyDic) {
      dailyDic.week = util.dateLater(dailyDic.date, 0);
      daily_forecast.push(dailyDic);
    });
    // for (var i = 0; i < weather.daily_forecast.length; i++) {
    //   var dailyDic = weather.daily_forecast[i];
    //   dailyDic.week = util.dateLater(dailyDic.date, 0);
    //   daily_forecast.push(dailyDic);
    // }

    // for (let key in weather.suggestion) {

    // }
    // 生活指数数组 按照指定顺序排列
    var suggestion = [];
    var comf = weather.suggestion.comf;
    comf.title = "舒适度";
    comf.id = 0;
    suggestion.push(comf);

    var drsg = weather.suggestion.drsg;
    drsg.title = "穿衣";
    drsg.id = 1;
    suggestion.push(drsg);

    var flu = weather.suggestion.flu;
    flu.title = "感冒";
    flu.id = 2;
    suggestion.push(flu);

    var sport = weather.suggestion.sport;
    sport.title = "运动";
    sport.id = 3;
    suggestion.push(sport);

    var trav = weather.suggestion.trav;
    trav.title = "旅游";
    trav.id = 4;
    suggestion.push(trav);

    var uv = weather.suggestion.uv;
    uv.title = "紫外线强度";
    uv.id = 5;
    suggestion.push(uv);

    var cw = weather.suggestion.cw;
    cw.title = "洗车";
    cw.id = 6;
    suggestion.push(cw);

    var air = weather.suggestion.air;
    air.title = "污染扩散";
    air.id = 7;
    suggestion.push(air);
    that.setData({
      weather: {
        hourly_forecast: hourly_forecast,
        daily_forecast: daily_forecast,
        aqi: weather.aqi.city,
        now: weather.now,
        astro: daily_forecast[0].astro,
        suggestion: suggestion,
        updateTime: weather.basic.update.loc
      },
      updateTimeHidden: false,
    });
    
    // 存储天气信息
    wx.setStorageSync('weather', that.data.weather)

    // 2秒后隐藏更新时间
    var timer = setTimeout(function() {
      that.setData({
        updateTimeHidden: true
      });
    }, 2000);
  },

  // 选择地理位置 获取天气
  chooseLocation: function(event) {
    var that = this;
    
    wx.chooseLocation({
      success: function(res) {
        if (res.name == "") {
          return
        }
        that.setData({
          isChoose: true
        })
        // 存储地理位置
        wx.setStorageSync("location", res.name)
        that.setData({
          location: res.name,
          latitude: res.latitude,
          longitude: res.longitude
        });
        that.getAddress(res.latitude, res.longitude, function(address, city) {
          that.getWeather(city);
        });
      },
    });
  },

  lifedetail: function(event) {
    var indexId = event.currentTarget.dataset.id;
    var title = event.currentTarget.dataset.title;
    var content = event.currentTarget.dataset.txt;

    wx.showModal({
      title: title,
      content: content,
      showCancel: false
    });
  },

  infoTap: function() {
    wx.navigateTo({
      url: '../setting/setting',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading();

    var city = wx.getStorageSync("city") || "睢阳区"
    this.getWeather(city);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})